﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;

namespace BookSleeve
{
    class AsyncMessageSocket : AsyncSocket
    {
        protected override void LogToConsole(string value)
        {
            connection.LogToConsole(value);
        }
        private readonly RedisConnectionBase connection;
        public AsyncMessageSocket(RedisConnectionBase connection)
        {
            this.connection = connection;
        }
        int db;
        int requestInProgress;
        protected override bool RequestData()
        {
            bool tookLock = false;
            try
            {
                tookLock = Interlocked.CompareExchange(ref requestInProgress, 1, 0) == 0;
                if(tookLock)
                {
                    LogToConsole("> Requesting data");
                    var result = connection.RequestData(ref db);
                    LogToConsole("< Requesting data");
                    return result;
                } else {
                    // re-entrant; no, we don't want that!
                    return false;
                }
            }
            finally
            {
                if (tookLock) Interlocked.Exchange(ref requestInProgress, 0);
            }
        }
        protected override bool ProcessIncoming(byte[] buffer, int offset, int count)
        {
            return connection.ProcessIncoming(buffer, offset, count);
        }
    }
}
